package com.payment.common.utils;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.Cookie;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import java.util.Random;


/**
 * http 工具类
 * @company neunn.com
 * @author songjie
 * @data 2019.1.2
 */
public class HttpUtil {

	private static final Logger logger = LoggerFactory.getLogger(HttpUtil.class);

	public static JSONObject postJson(String url, JSONObject json, String appkey, boolean isBasic) {
		PrintWriter out = null;
		BufferedReader in = null;
		URLConnection conn = null;
		String result = "";
		logger.info("push value = [" + json + "]");
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("content-type", "application/json;charset=utf-8");
			if (!"".equals(appkey) && null !=  appkey){
				if (isBasic){
					conn.setRequestProperty("Authorization", "Basic " + appkey);
				}else{
					conn.setRequestProperty("Authorization", appkey);
				}

			}

			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(json.toString());
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("send the request happen error！", e);
			result = "{\"error\":"+e.getMessage()+"}";
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error("close io happen error:", ex);
			}
		}
		return JSONObject.parseObject(result);
	}

	public static String postParam(String url, String params,String appkey) {
		PrintWriter out = null;
		BufferedReader in = null;
		URLConnection conn = null;
		String result = "";
		logger.info("push value = [" + params + "]");
		try {
			URL realUrl = new URL(url);
			// 打开和URL之间的连接
			conn = realUrl.openConnection();
			// 设置通用的请求属性
			conn.setRequestProperty("content-type", "application/json");
			if (!"".equals(appkey) && null !=  appkey){
				conn.setRequestProperty("Authorization", "Basic " + appkey);
			}

			// 发送POST请求必须设置如下两行
			conn.setDoOutput(true);
			conn.setDoInput(true);
			// 获取URLConnection对象对应的输出流
			out = new PrintWriter(conn.getOutputStream());
			// 发送请求参数
			out.print(params);
			// flush输出流的缓冲
			out.flush();
			// 定义BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}
		} catch (Exception e) {
			logger.error("send the request happen error！", e);
		}
		// 使用finally块来关闭输出流、输入流
		finally {
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				logger.error("close io happen error:", ex);
			}
		}
		return result;
	}

	public static String sendGet(String url,String param, String chatset) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			if (!StringUtils.isEmpty(param)){
				urlNameString += "?"+param;
			}
			System.out.println("请求地址:"+urlNameString);
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), chatset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}


		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}
			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	/**
	 * 带cookie
	 * @param url
	 * @param param
	 * @param chatset
	 * @param cookies
	 * @return
	 */
	public static String sendGet(String url, String param, String chatset,Cookie[] cookies) {
		String result = "";
		BufferedReader in = null;
		try {
			String urlNameString = url;
			if (!StringUtils.isEmpty(param)){
				urlNameString += "?"+param;
			}
			URL realUrl = new URL(urlNameString);
			// 打开和URL之间的连接
			URLConnection connection = realUrl.openConnection();
			// 设置通用的请求属性
			connection.setRequestProperty("accept", "*/*");
			connection.setRequestProperty("connection", "Keep-Alive");
			connection.setRequestProperty("user-agent",
					"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			if(null != cookies)
			{
				for (int i = 0; i < cookies.length; i++) {
					Cookie cook = cookies[i];
					connection.setRequestProperty(cook.getName(), cook.getValue().toString());
				}
			}

			// 建立实际的连接
			connection.connect();
			// 获取所有响应头字段
			Map<String, List<String>> map = connection.getHeaderFields();
			// 遍历所有的响应头字段
			for (String key : map.keySet()) {
				System.out.println(key + "--->" + map.get(key));
			}
			// 定义 BufferedReader输入流来读取URL的响应
			in = new BufferedReader(new InputStreamReader(connection.getInputStream(), chatset));
			String line;
			while ((line = in.readLine()) != null) {
				result += line;
			}


		} catch (Exception e) {
			System.out.println("发送GET请求出现异常！" + e);
			e.printStackTrace();
		}
		// 使用finally块来关闭输入流
		finally {
			try {
				if (in != null) {
					in.close();
				}


			} catch (Exception e2) {
				e2.printStackTrace();
			}
		}
		return result;
	}

	public static void main(String[] args) {
		// createToken();

		String param = null;
		String url = "http://maps.google.com/maps/api/geocode/json?latlng=13.82031,100.66471&language=zh-CN&sensor=false";
		System.out.println(HttpUtil.postParam(url, param,""));
	}

	public static void createToken() {

		String url = "http://localhost:18082/gateweb/push/bindtoken";
		String param = "promotion=gp&app_lan=English&app_ver=2.2.2.0.0.3&product_id=hotoday&uid=010116023454064548010000";
		String temp = "";
		Random random = new Random();
		for (int i = 0; i < 1100; i++) {
			String token = RandomString(15);
			temp = param + random.nextInt(10000000);
			try {
				Thread.sleep(10);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			System.out.println(temp);
			HttpUtil.postParam(url + "?" + temp + "&token=" + token, null,null);
		}

	}

	public static String RandomString(int length) {
		String str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
		Random random = new Random();
		StringBuffer buf = new StringBuffer();
		for (int i = 0; i < length; i++) {
			int num = random.nextInt(62);
			buf.append(str.charAt(num));
		}
		return buf.toString();
	}

	/**
	      * 实例化HttpClient
	      * maxTotal  最大连接数
	      * maxPerRoute  最大并发量
	      * socketTimeout  从服务器读取数据超时时间
	      * connectTimeout  和服务器建立连接超时时间
	      * connectionRequestTimeout  从连接池获取连接的超时时间
	      * @return
	      */
	public static HttpClient createDefaultHttpClient() {
	    int maxTotal = 10;
	    int maxPerRoute =5;
	    int socketTimeout = 3000;
		int connectTimeout = 3000;
	    int connectionRequestTimeout = 3000;
		RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(socketTimeout).setConnectTimeout(connectTimeout).setConnectionRequestTimeout(connectionRequestTimeout).build();
		PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
		//设置整个连接池最大连接数 根据自己的场景决定
		cm.setMaxTotal(maxTotal);
		 //这个是控制并发量的
		cm.setDefaultMaxPerRoute(maxPerRoute);
		CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).setDefaultRequestConfig(defaultRequestConfig).build();
		return httpClient;
	}


	public static String sendPut(String url, String authorization, JSONObject paramJson){
			HttpClient httpClient = createDefaultHttpClient();
			HttpPut httpPut = new HttpPut(url);
			//header存放 LPCC_TOKEN 
			if (!"".equals(authorization) && null !=  authorization){
				httpPut.addHeader("Authorization", "Basic " + authorization);
			}

			httpPut.addHeader("content-type", "application/json");

		 	StringEntity se = new StringEntity(paramJson.toString(), "utf-8");
		 	httpPut.setEntity(se);

		 	HttpResponse httpResponse = null;
			String res =null;
		 	try {
				httpResponse = httpClient.execute(httpPut);
				if(httpResponse!=null && 200 == httpResponse.getStatusLine().getStatusCode()){
					res =EntityUtils.toString(httpResponse.getEntity(), "utf-8");
				}else{
					res = "{\"error\":0}";
				}
			} catch (ClientProtocolException e) {
				logger.error(e.getMessage(), e);
				res = "{\"error\":"+e.getMessage()+"}";
			} catch (IOException e) {
				logger.error(e.getMessage(), e);
				res = "{\"error\":"+e.getMessage()+"}";
		}finally {
				if (null != httpResponse){
					httpResponse = null;
				}
				if (null != httpClient){
					httpClient = null;
				}
			}
		return res;
	 }

}
